package com.example.emergencyattempt01.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import com.example.emergencyattempt01.R;
import com.example.emergencyattempt01.activity.utils.NetWorkUtils;
import com.example.emergencyattempt01.activity.utils.ServerMessage;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import android.os.Handler;
import org.json.JSONException;
import org.json.JSONObject;

public class Ad_CheckingAdapter extends BaseAdapter {
    Context context;
    List<Map<String,Object>> itemList;
    ViewHolder viewHolder;


    // 无论什么网络请求，都要打包一个bid进去的
    String toServer;

    class ViewHolder
    {
        TextView bidField;
        TextView lidField;
        TextView uidField;
        TextView userNameField;
        TextView identityField;
        TextView ownBooksField;
        TextView bookNameField;
        TextView ISBNField;
        TextView borrowTimeField;

        Button refuse;
        Button permit;

        ImageView shapeMarker;
        TextView textMarker;

        TextView checkingTimeType;
    }
    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            int position=(int)msg.obj;
            switch (msg.what)
            {
                case REFUSE_BORROW_SUCCESS:
                  // 后移除此纪录，先弹出提示
                    Toast.makeText(context,"已拒绝借阅",Toast.LENGTH_SHORT).show();
                    itemList.remove(position);
                    break;

                case PERMIT_BORROW_SUCCESS:
                    Toast.makeText(context,"已同意借阅",Toast.LENGTH_SHORT).show();
                    itemList.remove(position);
                    break;
                case PERMIT_BORROW_DENY:
                    Toast.makeText(context,"该用户借阅数目已达5本",Toast.LENGTH_SHORT).show();
                    break;

                case REFUSE_RETURN_SUCCESS:
                    Toast.makeText(context,"已拒绝还书",Toast.LENGTH_SHORT).show();
                    itemList.remove(position);
                    break;

                case PERMIT_RETURN_SUCCESS:
                    Toast.makeText(context,"已同意还书",Toast.LENGTH_SHORT).show();
                    itemList.remove(position);
                    break;


                case PERMIT_CONTINUE_SUCCESS:
                    Toast.makeText(context,"已同意续借",Toast.LENGTH_SHORT).show();
                    itemList.remove(position);
                    break;

                case REFUSE_CONTINUE_SUCCESS:
                    Toast.makeText(context,"已拒绝续借",Toast.LENGTH_SHORT).show();
                    itemList.remove(position);
                    break;
                case SEND_FAIL:
                    Toast.makeText(context,"并没有什么响应...",Toast.LENGTH_SHORT).show();
                    break;
            }
            notifyDataSetChanged();
        }
    };
    // 一堆请求代码，反映各种情况的服务器响应情况
    final int REFUSE_BORROW_SUCCESS=0x001;
    final int PERMIT_BORROW_SUCCESS=0x003;
    final int PERMIT_BORROW_DENY=0x012;
    final int SEND_FAIL=0x004;

    final int REFUSE_RETURN_SUCCESS=0x005;
    final int PERMIT_RETURN_SUCCESS=0x007;

    final int PERMIT_CONTINUE_SUCCESS=0x009;
    final int REFUSE_CONTINUE_SUCCESS=0x011;





    public Ad_CheckingAdapter(Context context, List<Map<String, Object>> itemList) {
        this.context = context;
        this.itemList = itemList;
    }

    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
        return itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return (long)itemList.get(position).get("bid");
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=LayoutInflater.from(context);
        if(convertView==null)
        {
            convertView=inflater.inflate(R.layout.ad_checking_item,null);
            viewHolder=new ViewHolder();

            viewHolder.bidField=convertView.findViewById(R.id.ad_checking_bid);
            viewHolder.uidField=convertView.findViewById(R.id.ad_checking_uid);
            viewHolder.lidField=convertView.findViewById(R.id.ad_checking_lid);
            viewHolder.bookNameField=convertView.findViewById(R.id.ad_checking_bookName);
            viewHolder.borrowTimeField=convertView.findViewById(R.id.ad_checking_borrowTime);
            viewHolder.userNameField=convertView.findViewById(R.id.ad_checking_userName);
            viewHolder.identityField=convertView.findViewById(R.id.ad_checking_identity);
            viewHolder.ownBooksField=convertView.findViewById(R.id.ad_checking_ownBooks);
            viewHolder.ISBNField=convertView.findViewById(R.id.ad_checking_ISBN);
            viewHolder.shapeMarker=convertView.findViewById(R.id.ad_checking_shape_marker);
            viewHolder.textMarker=convertView.findViewById(R.id.ad_checking_text_marker);

            viewHolder.permit=convertView.findViewById(R.id.ad_checking_permit);
            viewHolder.refuse=convertView.findViewById(R.id.ad_checking_refuse);

            viewHolder.checkingTimeType=convertView.findViewById(R.id.ad_checking_time_type);

            convertView.setTag(viewHolder);
        }
        else
        {
            viewHolder=(ViewHolder) convertView.getTag();
        }

        // 以下内容为本模块显示的关键点
        // 获取各值
        long bid;
        long lid;
        long uid;
        String userName;
        String identity;
        String bookName;
        int ownBooks;
        String ISBN;
        long borrowTime;

        String borrowIsConfirmed;

        final String returnIsRequested;
        String returnIsConfirmed;

        final String continueIsRequested;
        String continueIsConfirmed;


        uid=(long)itemList.get(position).get("uid");
        bid=(long)itemList.get(position).get("bid");
        lid=(long)itemList.get(position).get("lid");

        borrowTime=(long)itemList.get(position).get("borrowTime");

        userName=(String)itemList.get(position).get("userName");
        identity=(String)itemList.get(position).get("identity");
        bookName=(String)itemList.get(position).get("bookName");
        ownBooks=(int)itemList.get(position).get("ownBooks");
        ISBN=(String)itemList.get(position).get("ISBN");

        borrowIsConfirmed=(String)itemList.get(position).get("borrowIsConfirmed");

        returnIsRequested=(String)itemList.get(position).get("returnIsRequested");
        returnIsConfirmed=(String)itemList.get(position).get("returnIsConfirmed");

        continueIsRequested=(String)itemList.get(position).get("continueIsRequested");
        continueIsConfirmed=(String)itemList.get(position).get("continueIsConfirmed");

        // 对单纯的文字部分设值
        viewHolder.uidField.setText("uid:"+uid);
        viewHolder.bidField.setText("借阅号:"+bid);
        viewHolder.lidField.setText("馆藏号:"+lid);
        viewHolder.userNameField.setText(userName);
        viewHolder.identityField.setText(identity);
        viewHolder.bookNameField.setText(bookName);
        if(ownBooks<=5)
        viewHolder.ownBooksField.setText(ownBooks+"本");
        else
            viewHolder.ownBooksField.setText("5本");
        viewHolder.ISBNField.setText(ISBN);

        // 对时间进行一个处理
        String borrowTimeDisplay=millisToString(borrowTime);
        viewHolder.borrowTimeField.setText(borrowTimeDisplay);
        // 处理特殊显示情况
        if(!returnIsRequested.equals("已请求")&&!continueIsRequested.equals("已请求"))
            // 表示借阅请求
        {
            viewHolder.checkingTimeType.setText("申请时间");
            viewHolder.shapeMarker.setImageResource(R.drawable.blue_circle);
            viewHolder.textMarker.setText("借");
        }
        // 表示还书或者续借请求
        else
        {
            viewHolder.checkingTimeType.setText("借阅时间");
            // 此况下，还书与续借只能二者择其一，属于平行分支关系
            if(returnIsRequested.equals("已请求"))
            {
                viewHolder.shapeMarker.setImageResource(R.drawable.red_circle);
                viewHolder.textMarker.setText("还");
            }
            else if(continueIsRequested.equals("已请求"))
            {
                viewHolder.shapeMarker.setImageResource(R.drawable.orange_circle);
                viewHolder.textMarker.setText("续");
            }
        }
        /** 以上内容学生端也可以用到，但是整体有所区别
         * 即学生端会针对各种请求批示与否，决定按钮类型，管理员端不用考虑这个
         */
        // 在此之前，需要打包一个通用的东西：bid
        try {
            JSONObject object=new JSONObject();
            object.put("bid",bid);
            toServer=String.valueOf(object);
        }catch (JSONException e){e.printStackTrace();}

        // 建立一个中间量
        final int i=position;
        // 按钮
        // 拒绝
        viewHolder.refuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                builder.setMessage("确定拒绝吗？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread()
                        {
                            @Override
                            public void run() {
                                try {
                                    // 确认拒绝了
                                    // 区分一下是拒绝什么
                                    if(!returnIsRequested.equals("已请求")&&!continueIsRequested.equals("已请求"))
                                    // 拒绝借书
                                    {
                                        ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/borrow_book_refuse");
                                        int code=serverMessage.getRespondCode();
                                        if(code==200)
                                        {
                                            Message message=new Message();
                                            message.what=REFUSE_BORROW_SUCCESS;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                        else
                                        {
                                            Message message=new Message();
                                            message.what=SEND_FAIL;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                    }
                                    else if (returnIsRequested.equals("已请求"))
                                    // 拒绝还书
                                    {
                                        ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/return_book_refuse");
                                        int code=serverMessage.getRespondCode();
                                        if(code==200)
                                        {
                                            Message message=new Message();
                                            message.what=REFUSE_RETURN_SUCCESS;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                        else
                                        {
                                            Message message=new Message();
                                            message.what=SEND_FAIL;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                    }
                                    else if(continueIsRequested.equals("已请求"))
                                    // 拒绝续借
                                    {
                                        ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/continue_refuse");
                                        int code=serverMessage.getRespondCode();
                                        if(code==200)
                                        {
                                            Message message=new Message();
                                            message.what=REFUSE_CONTINUE_SUCCESS;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                        else
                                        {
                                            Message message=new Message();
                                            message.what=SEND_FAIL;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                    }
                                }catch (JSONException e){e.printStackTrace();}
                                catch (IOException e){e.printStackTrace();
                                    Message message=new Message();
                                    message.what=SEND_FAIL;
                                    message.obj=i;
                                    handler.sendMessage(message);}
                            }
                        }.start();
                    }
                });
                builder.create().show();
            }
        });

        // 同意
        viewHolder.permit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                builder.setMessage("确定同意吗？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread()
                        {
                            @Override
                            public void run() {
                                try {
                                    // 确认同意了
                                    // 区分一下是同意什么
                                    if(!returnIsRequested.equals("已请求")&&!continueIsRequested.equals("已请求"))
                                    // 同意借书
                                    {
                                      ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/borrow_book_permit");
                                        int code=serverMessage.getRespondCode();
                                        if(code==200)
                                        {
                                            String fromServer=(String) serverMessage.getFromServer();
                                            JSONObject object=new JSONObject(fromServer);
                                            boolean can=object.getBoolean("can");
                                            if(can) {// 可以同意
                                                Message message = new Message();
                                                message.what = PERMIT_BORROW_SUCCESS;
                                                message.obj = i;
                                                handler.sendMessage(message);
                                            }
                                            else
                                            {
                                                Message message = new Message();
                                                message.what = PERMIT_BORROW_DENY;
                                                message.obj = i;
                                                handler.sendMessage(message);
                                            }
                                        }
                                        else
                                        {
                                            Message message=new Message();
                                            message.what=SEND_FAIL;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                    }
                                    else if (returnIsRequested.equals("已请求"))
                                    // 同意还书
                                    {
                                        ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/return_book_permit");
                                        int code=serverMessage.getRespondCode();
                                        if(code==200)
                                        {
                                            Message message=new Message();
                                            message.what=PERMIT_RETURN_SUCCESS;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                        else
                                        {
                                            Message message=new Message();
                                            message.what=SEND_FAIL;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                    }
                                    else if(continueIsRequested.equals("已请求"))
                                    // 同意续借
                                    {
                                        ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/continue_permit");
                                        int code=serverMessage.getRespondCode();
                                        if(code==200)
                                        {
                                            Message message=new Message();
                                            message.what=PERMIT_CONTINUE_SUCCESS;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                        else
                                        {
                                            Message message=new Message();
                                            message.what=SEND_FAIL;
                                            message.obj=i;
                                            handler.sendMessage(message);
                                        }
                                    }
                                }catch (JSONException e){e.printStackTrace();}
                                catch (IOException e){e.printStackTrace();
                                    Message message=new Message();
                                    message.what=SEND_FAIL;
                                    message.obj=i;
                                    handler.sendMessage(message);}
                            }
                        }.start();
                    }
                });
                builder.create().show();
            }
        });


        return convertView;
    }


    private String millisToString(long timeInMillis) {
        //新建一个calendar对象帮助转化出年月日时分秒
        Calendar calendar=Calendar.getInstance();
        calendar.setTimeInMillis(timeInMillis);
        /**
         * calendar中月份是从0起的
         */
        String year=unify( calendar.get(Calendar.YEAR));
        String month=unify( calendar.get(Calendar.MONTH)+1);
        String day=unify( calendar.get(Calendar.DATE));
        String hour=unify( calendar.get(Calendar.HOUR_OF_DAY));
        String minute=unify( calendar.get(Calendar.MINUTE));
        String second=unify( calendar.get(Calendar.SECOND));

        String target=year+"/"+month+"/"+day+"  "+hour+":"+minute+":"+second;
        return  target;
    }
    private String unify(int num)
    {
        String target=null;
        if(num<10)
        {
            target="0"+num;
        }
        else
            target=""+num;
        return target;
    }
}
